import {
  Pool,
  Post,
  Ws,
  Parpath,
  APPrequest,
  query,
  addToken,
  getToken,
  getJson
} from '../../plugins/import'
@Parpath('/user')
export default class User {
  constructor () {}
  /**
   * 登录查询
   * @param param0 
   * @param pool 
   */
  @Post('/login')
  doLogin ({ req, res }: APPrequest, pool: Pool) {
    const { userAccount, userPassword } = req.body
    if (userAccount && userPassword) {
      const sqlStr = `SELECT user_id FROM t_user WHERE user_account='${userAccount}' AND user_password='${userPassword}'`
      query(sqlStr, pool).then(results => {
        if ((<any>results).length > 0) {
          const data = (<any>results)[0]
          const userId = data.user_id
          const token = addToken(userId)
          res.json(getJson('true', 200, '查询成功', {
            'token': token
          }))
        } else {
          res.json(getJson('false', 500, '账号或密码错误，请重新输入'))
        }
      }).catch(error => {
        res.json(getJson('false', 500, '数据库错误，请联系管理员'))
      })
    }
  }
  /**
   * 获取用户信息
   * @param param0 
   * @param pool 
   */
  @Post('/userInfo')
  doUserInfo ({ req, res }: APPrequest, pool: Pool) {
    res.json(getJson('true', 200, '查询成功', {
      'token': '123456789'
    }))
  }

  /* 测试Ws */
  @Ws('/wsTest', 8081)
  wsTest ({socket, ws}: any) {
    socket.on('message', function (msg: any) {
      ws.clients.forEach(function each(client: any) {
        client.send(123)
      })
    })
  }
}
